package com.eryos.android.cigarettecounter.ui;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import java.io.IOException;
import java.net.UnknownHostException;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.eryos.android.cigarettecounter.R;
import com.eryos.android.cigarettecounter.charts.Chart;
import com.eryos.android.cigarettecounter.tool.GoogleAnalyticsProvider;

public class ChartPopup extends Dialog{

    private final static String LOG_TAG = "ChartPopup";
    private Context    context;

    /* UI Elements */
    private ImageView    chartFullScreen;
    private Button       shareButton;
    private Chart       chart;
    private Bitmap       bmp;

    /**
     * 
     * @param context
     * @param _chart
     */
    public ChartPopup(Context context, Chart _chart) {
        super(context);
        Log.w(LOG_TAG, getClass().getSimpleName()+" : new ChartPopup()");

        /* Define & Initialize attributes */
        this.context = context;
        this.setChart(_chart);
        this.setContentView(R.layout.chart_dialog);
        this.setTitle(_chart.getTitle());

        /* Retrieve UI Components */
        chartFullScreen = (ImageView) findViewById(R.id.popup_image);      
        shareButton     = (Button) findViewById(R.id.popup_share_button);
        shareButton.setEnabled(false);

        /* Download chart from Google API */
        new DownloadFilesTask().execute(_chart.getURL());

        /* Show Popup */
        this.show();

        /* Listener for closing Popup */
        chartFullScreen.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                dismiss();
                return false;
            }
        });

        /* Listener for Share button */
        shareButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent e) {
                if ( e.getAction() == MotionEvent.ACTION_DOWN ) {
                    Log.d("Popup", "Click");
                    shareGraphic();
                }
                return true;
            }
        });
    }

    /**
     * Save the current bitmap on SDCard, et raise an intent to share the picture
     */
    public void shareGraphic(){
        Log.w(LOG_TAG, "shareGraphic");
        
        /* Create new ACTION_SEND intent */
        Intent shareIntent = new Intent(Intent.ACTION_SEND);

        /* Define type of content */
        shareIntent.setType("image/jpeg");
        shareIntent.setFlags(0x1/*Intent.FLAG_ACTIVITY_NEW_TASK*/);
        shareIntent.setComponent(ComponentName.unflattenFromString("com.google.android.apps.plus/com.google.android.apps.plusone.app.ComposeUpdateActivity"));

        /* Write image to file on SD Card */
        String uri = Chart.writeBitmapToSD(bmp, chart.getTitle().replaceAll(" ", "_"));

        /* Attach Title/Text/Subjet to Intent */
        shareIntent.putExtra(Intent.EXTRA_TITLE, "Here's my smoking stats ... (generated from CigaretteCounter)");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Here's my smoking stats ... (generated from CigaretteCounter)");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "Here's my smoking stats ... (generated from CigaretteCounter)");

        /* Attach file (with URI) to Intent */
        Uri attachedFile  = Uri.parse("file://"+uri);
        shareIntent.putExtra(Intent.EXTRA_STREAM, attachedFile);

        /* Track Google Analytics Event */
        GoogleAnalyticsProvider.trackEvent("Share", "Chart");

        /* Raise Intent */
        context.startActivity(Intent.createChooser(shareIntent, "Choose an appli to send your chart"));
    }

    /**
     * Return chart defined for the popup
     * @return
     */
    public Chart getChart() {
        return chart;
    }

    /**
     * Change the chart of the popup
     * @param chart
     */
    public final void setChart(Chart chart) {
        this.chart = chart;
    }

    // ######################################################################## // 
    // ######################################################################## // 
    // ######################################################################## // 
    
    /**
     * Background task used to download chart and convert to bitmap
     */
    private class DownloadFilesTask extends AsyncTask<String, Integer, Bitmap> {

        Bitmap errorBitmap = null;

        /**
         * Step 1 - invoked on the UI thread immediately after the task is executed.
         * This step is normally used to setup the task, for instance by showing a progress bar in the user interface
         */
        protected void onPreExecute() {
            chartFullScreen.setImageDrawable(context.getResources().getDrawable(R.drawable.loader/*.eryos*/));
        }

        /**
         * Step 2 - invoked on the background thread immediately after onPreExecute() finishes executing.
         * This step is used to perform background computation that can take a long time
         */
        protected Bitmap  doInBackground(String... urls) {

            try {
                bmp = Chart.downloadChartAsBitmap(context, urls[0]);
                return bmp;
            } catch (UnknownHostException e) {
                return errorBitmap;
            } catch (IOException e) {
                Log.e(getClass().getSimpleName(), "doInBackground Error ", e);
                return errorBitmap;
            }

        }

        /**
         * Step 3 - invoked on the UI thread after the background computation finishes.
         * The result of the background computation is passed to this step as a parameter.
         */
        protected void onPostExecute(Bitmap  result) {
            if ( result != null ){
                chartFullScreen.setImageBitmap(result);
                shareButton.setEnabled(true);
                Toast.makeText(context, "download OK", Toast.LENGTH_SHORT);
            } else {
                chartFullScreen.setImageDrawable(context.getResources().getDrawable(R.drawable.eryos)); // TODO change bitmap
                Toast.makeText(context, "Sorry, an error occurs while downloading chart", Toast.LENGTH_LONG);
            }
        }
    }
}
